package com.victor9ac.mashup.elasticsearch.aop;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.victor9ac.mashup.api.MashupDataType;
import com.victor9ac.mashup.elasticsearch.annotation.ElasticSearchPersistence;
import com.victor9ac.mashup.elasticsearch.tasks.ElasticSearchOperation;
import com.victor9ac.mashup.es.threadpool.MashupThreadPool;

@Component
public class ElasticSearchPjp {

	private static final String INDEX_POSTFIX_NAME = "-index2";

	@Autowired
	ElasticSearchOperation elasticSearchOperation;
	
	@Autowired
	MashupThreadPool threadPool;
	
	public Object saver(ProceedingJoinPoint pjp) throws Throwable {

		Object result = null;

		try {

			System.out.println("executing ES persistence annotation ...");
			
			result = pjp.proceed();
			
			if (result != null){
				
				MashupDataType mashupDataType = this.getMashupDataType(pjp);
				String indexName = getElasticIndexName(mashupDataType);
				threadPool.run(this.elasticSearchOperation,mashupDataType,indexName, result);
			}
			
			System.out.println("exit from ES persistence annotation ...");

		} catch (Exception e) {
			System.out.println(":( ....error executing indexer Elastic annotation ");
			e.printStackTrace();
			
		}finally{
//			pjp.proceed();
		}

		return result;
	}

	private String getElasticIndexName(MashupDataType mashupDataType) {
		String indexName = mashupDataType.toString().toLowerCase()+INDEX_POSTFIX_NAME;
		return indexName;
	}

	private MashupDataType getMashupDataType(ProceedingJoinPoint pjp)
			throws NoSuchMethodException {
		ElasticSearchPersistence annotation = getAnnotation(pjp, pjp.getSignature());
		MashupDataType mashupDataType = annotation.indexType();
		return mashupDataType;
	}

	private ElasticSearchPersistence getAnnotation(ProceedingJoinPoint pjp,
			final Signature signature) throws NoSuchMethodException {
		
		org.aspectj.lang.reflect.MethodSignature msig = (org.aspectj.lang.reflect.MethodSignature)signature;
		
		final String methodName = pjp.getSignature().getName();
		Method method = msig.getMethod();
		ElasticSearchPersistence myAnnotation = null;
		if (method.getDeclaringClass().isInterface()) {

			method = pjp.getTarget().getClass()
					.getDeclaredMethod(methodName, method.getParameterTypes());

		}

		Annotation[] annotations = method.getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation instanceof ElasticSearchPersistence) {
				myAnnotation = (ElasticSearchPersistence) annotation;

			}
		}
		return myAnnotation;
	}


}
